/**
* 作者:ZHX
* 日期:2024/5/15
* 描述:
*/
<template>
  <div>
    <el-card style="margin-bottom: 5px">
      <el-row>
        <el-col :span="24">
          <el-button type="primary" @click="addDialogVisible = true;">添加配置</el-button>
        </el-col>
      </el-row>
      <yg-table ref="ygtable" :columns="columns" :loading="loadingShow" :table-list="TableList"> <!-- 在这里增加操作列 -->
        <template v-slot:action="scope">
          <el-table-column align="center" label="操作" width="180">
            <template #default="scope">
              <div style="display: flex;align-items: center">
                <el-button circle icon="EditPen" type="primary" @click="editFunction(scope.row)"></el-button>
                <el-button circle icon="Delete" type="danger" @click="deleteFunction(scope.row)"></el-button>
                <el-button circle icon="Download" type="primary" @click="downloadJSON(scope.row)"></el-button>
                <el-upload :show-file-list="false" accept=".json" :auto-upload="false" :limit="1"
                           :on-change="handleOnchange" style="display: inline-block;margin-left:12px;">
                  <el-button circle icon="Upload" type="primary" @click="currentRow=scope.row"></el-button>
                </el-upload>
              </div>

            </template>
          </el-table-column>
        </template>
      </yg-table>
    </el-card>
    <!-- 添加用户弹窗 -->
    <el-dialog v-model="addDialogVisible" :close-on-click-modal="false" draggable title="添加配置" width="60%"
               @close="resetForm(addForm)">
      <yg-from ref="addForm" :customRules="addFormRules" :formData="addFromData" :formObj="addFromObj"></yg-from>
      <span class="dialog-footer" style="margin-top: 100px">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addConfirm">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改用户信息 -->
    <el-dialog v-model="editDialogVisible" :close-on-click-modal="false" draggable title="修改配置" width="60%"
               @close="resetForm(editForm)">
      <yg-from ref="editForm" :customRules="editFormRules" :formData="editFromData" :formObj="editFromObj"></yg-from>
      <span slot="footer" class="dialog-footer" style="margin-top: 100px">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editConfirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import YgTable from "@/components/Table/YgTable.vue";
import YgFrom from "@/components/Form/YgFrom.vue";
import {setMessageCallback, publishMsg, removeMessageCallback, checkSpecialId,} from "@/mqtt";
import {onMounted, reactive, toRefs, onBeforeUnmount} from 'vue';
import {SCADA_MSG} from "@/utils/Menu/menu.js";
// import {useStore} from "vuex";
// import {useRouter} from "vue-router";
import {ElMessage, ElMessageBox} from 'element-plus'

export default {
  //import引入的组件需要注入到对象中才能使用
  name: "ParamUser",
  components: {
    YgTable,
    YgFrom,
  },
  setup() {
    // const router = useRouter();
    // const store = useStore()
    // 使用 reactive 定义复杂数据
    const data = reactive({
      ygtable: null,
      currentRow: {},
      loadingShow: false, //加载表格数据
      addDialogVisible: false, //添加用户弹窗显隐
      editDialogVisible: false, //修改用户信息
      columns: [
        {
          prop: "name",
          label: "名称",
          align: "left",
          width: 100
        },
        {
          prop: "json",
          label: "配置",
        },
        {slot: "action", align: "center"},
      ],
      TableList: [],
      addFormRules: {
        topic: [
          {required: true, message: '请输入name', trigger: 'change'},
        ],
        desc: [
          {required: true, message: '请输入配置', trigger: 'change'},
        ],
      },
      addFromObj: [
        {
          input: true, //是input
          label: "名称", //字段
          prop: "name", //字段名
          width: 24, //参考el-col
          placeholder: "请输入名称",
          disabled: false, //是否禁用
          labelWidth: "80px",
        },
        {
          textarea: true, //是input
          // textarea:true,
          rows: 3,
          label: "配置", //字段
          prop: "json", //字段名
          width: 24, //参考el-col
          placeholder: "请输入配置",
          disabled: false, //是否禁用
          labelWidth: "80px",
        },
      ],
      addFromData: {
        name: "",
        json: "",
      },
      editFormRules: {
        topic: [
          {required: true, message: '请输入name', trigger: 'change'},
        ],
        desc: [
          {required: true, message: '请输入配置', trigger: 'change'},//验证手机
        ],
      },
      editFromObj: [
        {
          input: true, //是input
          label: "名称", //字段
          prop: "name", //字段名
          width: 24, //参考el-col
          placeholder: "请输入配置名称",
          disabled: true, //是否禁用
          labelWidth: "80px",
        },
        {
          textarea: true, //是input
          rows: 3,
          label: "配置", //字段
          prop: "json", //字段名
          width: 24, //参考el-col
          placeholder: "请输入配置",
          disabled: false, //是否禁用
          labelWidth: "80px",
        },
      ],
      editFromData: {
        name: "",
        json: "",
      },
      addForm: null,
      editForm: null,
    });

    const handleOnchange = (uploadFile) => {
      let file = uploadFile.raw;  // 获取文件信息
      const fileReader = new FileReader();
      fileReader.readAsText(file);  // 开始读取文件的内容为二进制
      fileReader.onload = (ev) => { // 读取完成,对数据进行自己的操作
        const json = ev.target?.result; //获取内容
        let newMsg = {webMsgType: SCADA_MSG.scada_param_json, funCode: 3,};
        data.currentRow.json = json
        newMsg.data = data.currentRow;
        publishMsg(newMsg);
        data.editDialogVisible = false;
      };
    };

    function downloadJSON(item) {
      // 将数据转换为JSON字符串
      const json = item.json
      // 创建一个Blob对象，类型为octet/stream
      const blob = new Blob([json], {type: 'application/json'});
      // 创建一个指向Blob对象的URL
      const url = URL.createObjectURL(blob);
      // 创建一个a标签用于下载
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', '配置.json');
      document.body.appendChild(link);
      // 触发下载
      link.click();
      // 清理
      document.body.removeChild(link);
      URL.revokeObjectURL(url);
    }

    function editFunction(row) {
      data.editDialogVisible = true;
      data.editFromData.name = row.name;
      data.editFromData.json = row.json;
      data.editFromData._id = row._id;
    }

    function deleteFunction(item) {
      ElMessageBox.confirm(`将要删除名称为${item.name}的配置。是否确定删除?`, "删除配置", {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        let newMsg = {webMsgType: SCADA_MSG.scada_param_json, funCode: 2,};
        newMsg.data = {_id: item._id};
        publishMsg(newMsg);
      }).catch(() => ElMessage.info("已取消删除"))
    }

    function editConfirm() {
      let newMsg = {webMsgType: SCADA_MSG.scada_param_json, funCode: 3,};
      newMsg.data = data.editFromData;
      publishMsg(newMsg);
      data.editDialogVisible = false;
    }

    function onMessage(topic, msg) {
      if ((msg.webMsgType == SCADA_MSG.scada_param_json) && checkSpecialId(msg)) {
        if (msg.retCode != 0) {
          ElMessage.error(msg.retMsg);
        } else {
          data.TableList = msg.data;
          data.loadingShow = false;
          switch (msg.funCode) {
            case 1:
              ElMessage.success("添加成功");
              break;
            case 2:
              ElMessage.success("删除成功");
              break;
            case 3:
              ElMessage.success("修改成功");
              break;
            default:
              break;
          }
        }
      }
    }


    function addConfirm() {
      if (data.addForm.submitForm()) {
        let newMsg = {webMsgType: SCADA_MSG.scada_param_json, funCode: 1,};
        newMsg.data = data.addFromData;
        publishMsg(newMsg);
        data.addDialogVisible = false;
      }
    }

    const resetForm = (formEl) => {
      if (!formEl) return
      formEl.resetForm()
    }

    onMounted(() => {
      setMessageCallback(onMessage);
      publishMsg({webMsgType: SCADA_MSG.scada_param_json, funCode: 0,});
      data.loadingShow = true;
    })

    onBeforeUnmount(() => {
      removeMessageCallback(onMessage);
    })
    return {
      ...toRefs(data),
      resetForm,
      editFunction,
      deleteFunction,
      editConfirm,
      onMessage,
      addConfirm,
      downloadJSON,
      handleOnchange
    }
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-card__body {
  padding: 5px 5px 5px 5px;
}
</style>
